﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
namespace DateBaseSyshronous
{
    /// <summary>
    /// 主数据库类
    /// </summary>
    public class MasterDataBase : MysqlBase
    {
        public MasterDataBase(string connectString)
        {
            this.ConnectionString = connectString;
        }

        public DataSet GetDataSetFromTable(string sqlString)
        {
            return MySqlHelper.ExecuteDataset(connectionString, sqlString);
        }


        public bool UpdateDataSetFromTable(DataSet ds, string tableName, string ModelType) {
            switch (ModelType) {
                case "entire": return UpdateEntire(ds, tableName);
                case "section":
                default:
                    return UpdateSection(ds, tableName);
            }
        }

        public bool UpdateEntire(DataSet ds, string tableName) {
            try {
                //清空表
                var delsql = @"truncate table {0}";
                delsql = string.Format(delsql, tableName);
                MySqlHelper.ExecuteNonQuery(ConnectionString, delsql);
                //插入新数据
                updateData(connectionString, GetDataTableStuct(tableName), ds, tableName);
                return true;
            }
            catch (Exception ex) {
                return false;
            }
        }

        private bool UpdateSection(DataSet ds, string tableName) {
            try {
                updateData(connectionString, GetDataTableStuct(tableName), ds, tableName);
                return true;
            }
            catch (Exception ex) {
                return false;
            }
        }

        private string GetDataTableStuct(string tableName) {
            var sqlstr = @"SELECT * FROM {0} WHERE 1=2";
            return string.Format(sqlstr, tableName);
        }

        private bool updateData(string connectionString, string commandText, DataSet ds, string tablename) {
            MySqlConnection cn = new MySqlConnection(connectionString);
            cn.Open();
            MySqlDataAdapter da = new MySqlDataAdapter(commandText, cn);
            MySqlCommandBuilder cb = new MySqlCommandBuilder(da);
            DataSet ds2 = new DataSet();
            da.Fill(ds2, tablename);
            object[] obj = new object[ds.Tables[0].Columns.Count];
            foreach (DataRow row in ds.Tables[0].Rows) {
                row.ItemArray.CopyTo(obj, 0);
                ds2.Tables[tablename].Rows.Add(obj);
            }
            da.Update(ds2, tablename);
            cn.Close();
            return false;
        }

    }
}
